package nl.ekok.Kentekencheck;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.InputFilter;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnKeyListener;
import android.view.View.OnTouchListener;
import android.widget.EditText;
import android.widget.Toast;

public class Kentekencheck extends Activity {

	public static final String AUTO_DETAILS = "auto_details";
	protected static final Uri AUTOWEEK_NL_URL = Uri.parse("http://www.autoweek.nl");
	private ProgressDialog progressDialog;
	
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        
        setContentView(R.layout.main);
        
        // Allow only letters, numbers and dashes as input
        EditText kenteken = (EditText)findViewById(R.id.kenteken);
        kenteken.setFilters(new InputFilter[] { new KentekenInputFilter(), new InputFilter.LengthFilter(8) });
        
        // And format the input as well
        kenteken.setOnKeyListener(new OnKeyListener() {

			public boolean onKey(View v, int keyCode, KeyEvent event) {
				if (event.getAction() == KeyEvent.ACTION_UP) {
					
					// If we have 6 real characters...
					EditText k = ((EditText)v);
					String out = k.getText().toString().replace("-", "");
					if (out.length() == 6) {

						// Add dashes appropriately (AA-00-AA or 0-AAA-00)
						if ((Character.isDigit(out.charAt(4)) && Character.isDigit(out.charAt(5))) ||
							(Character.isLetter(out.charAt(4)) && Character.isLetter(out.charAt(5)))) {
							out = out.substring(0, 2) + '-' + out.substring(2, 4) + '-' + out.substring(4);
						} else {
							out = out.substring(0, 2) + '-' + out.substring(2, 5) + '-' + out.substring(5);
						}
						k.setText(out);

					}
				}
				return false;
			}
        	
        });

        findViewById(R.id.search).setOnClickListener(new OnClickListener() {

			public void onClick(View v) {
				
				// Start a search
				StartSearch();
			}
        	
        });
        
        // Start autoweek.nl website on image touch
        findViewById(R.id.poweredBy).setOnTouchListener(new OnTouchListener() {

			public boolean onTouch(View v, MotionEvent event) {
				// Intent on Autoweek.nl
				startActivity(new Intent("android.intent.action.VIEW", AUTOWEEK_NL_URL));
				return true;
			}
        	
        });
    }
    
    private void StartSearch() {
    	
    	// Retrieve and filter input text
    	EditText kentekenBox = (EditText) findViewById(R.id.kenteken);
    	String query = kentekenBox.getText().toString();
    	query = query.trim().replace("-", "");
    	
    	// Any (valid) input?
    	if (query.equals("") || query.length() != 6) {
    		Toast.makeText(this, R.string.invalid_input, Toast.LENGTH_LONG).show();
    		return;
    	}
    	
		progressDialog = ProgressDialog.show(this, "", getResources().getText(R.string.loading), true);
    	
    	// Search Autoweek for this query
    	final Handler resultHandler = new Handler() {
		   @Override
		   public void handleMessage(Message msg) {
			   switch (msg.what) {
			   case AutoweekFetcher.RESULT_OK:
				   onFetchResult((Auto) msg.obj);
				   return;
			   default:
				   onFetchError(msg.what);
				   return; 
			   }
			   
		   }

    	};
    	AutoweekFetcher fetch = new AutoweekFetcher(resultHandler, query);
    	fetch.start();
    	
    }
    
    private void onFetchResult(Auto auto) {

    	progressDialog.dismiss();
		
    	// Start details activity screen
    	Intent i = new Intent(this, KentekenDetails.class);
    	i.putExtra(AUTO_DETAILS, auto);
    	startActivity(i);
    	
    	// Empty previous input
    	((EditText) findViewById(R.id.kenteken)).setText("");
    }

	private void onFetchError(int what) {

		progressDialog.dismiss();
		
		// Error fetching the car details...
		if (what == AutoweekFetcher.RESULT_NO_VALID_RESPONSE) {
			Toast.makeText(this, R.string.no_result, Toast.LENGTH_LONG).show();
		} else {
			Toast.makeText(this, R.string.connection_error, Toast.LENGTH_LONG).show();
		}
		
	}
	
}